package com.atguigu.eduservice.service.impl;

import com.alibaba.excel.EasyExcel;
import com.atguigu.eduservice.Listener.SubjectExcelListener;
import com.atguigu.eduservice.entity.EduSubject;
import com.atguigu.eduservice.entity.excel.ExcelSubjectData;
import com.atguigu.eduservice.entity.subject.OneSubject;
import com.atguigu.eduservice.entity.subject.TwoSubject;
import com.atguigu.eduservice.mapper.EduSubjectMapper;
import com.atguigu.eduservice.service.EduSubjectService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.beans.ExceptionListener;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 课程科目 服务实现类
 * </p>
 *
 * @author testjava
 * @since 2020-06-30
 */
@Service
public class EduSubjectServiceImpl extends ServiceImpl<EduSubjectMapper, EduSubject> implements EduSubjectService {

    @Override
    public void saveSubject(MultipartFile file, EduSubjectService eduSubjectService) {

        try {
            InputStream in = file.getInputStream();

            EasyExcel.read(in, ExcelSubjectData.class, new SubjectExcelListener(eduSubjectService)).sheet().doRead();
        } catch (Exception e) {

        }


    }

    @Override
    public List<OneSubject> getAllOneTwoSubject() {
        //查询一级分类，id等于0
        QueryWrapper<EduSubject> wapperOne = new QueryWrapper<>();
        wapperOne.eq("parent_id", 0);
        List<EduSubject> oneSubjects = baseMapper.selectList(wapperOne);

        //查询二级分类，id不等于0
        QueryWrapper<EduSubject> wapperTwo = new QueryWrapper<>();
        wapperTwo.ne("parent_id", 0);
        List<EduSubject> twoSubjects = baseMapper.selectList(wapperTwo);

        //创建集合，封装一级分类
        List<OneSubject> finalSubject = new ArrayList<>();

        //封装一级分类
        for (int i = 0; i < oneSubjects.size(); i++) {//
            EduSubject eduSubject = oneSubjects.get(i);

            OneSubject oneSubject = new OneSubject();

//            oneSubject.setId(eduSubject.getId());
//            oneSubject.setTitle(eduSubject.getTitle());

            BeanUtils.copyProperties(eduSubject, oneSubject);
            finalSubject.add(oneSubject);

            //创建集合，封装二级分类
            List<TwoSubject> twofinalSubject = new ArrayList<>();

            for (int j = 0; j < twoSubjects.size(); j++) {
                EduSubject tSubject = twoSubjects.get(j);
                if (tSubject.getParentId().equals(eduSubject.getId())) {
                    TwoSubject twoSubject = new TwoSubject();
                    BeanUtils.copyProperties(tSubject, twoSubject);
                    twofinalSubject.add(twoSubject);
                }
            }
            oneSubject.setChildren(twofinalSubject);
        }

        return finalSubject;
    }
}
